﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ZDSoft.LMS.Core;
using ZDSoft.LMS.Service;
using ZDSoft.LMS.Domain;
using ZDSoft.LMS.Web.Apps;
using NHibernate.Criterion;

namespace ZDSoft.LMS.Web.Controllers
{
    public class TransportOrderController : UcController
    {
        /// <summary>
        /// 分页展示user信息,默认为第一页
        /// </summary>
        /// <param name="pageIndex">页码</param>
        /// <param name="userName">查询条件，用户名</param>
        public ActionResult Index(int pageIndex = 1)
        {
            int count = 0;//用于存放满足条件的记录总数
            IList<ICriterion> listQuery = GetCondition();//获取查询条件
            IList<Order> listOrder = new List<Order>() { new Order("ID", true) };//设置一个排序集合，new Order("ID", true)表示：根据ID排序,true代表升序,false代表降序
            IList<TransportOrder> list = Container.Instance.Resolve<ITransportOrderService>().GetPaged(listQuery, listOrder, pageIndex, PagerHelper.PageSize, out count);

            PageList<TransportOrder> pageList = list.ToPageList<TransportOrder>(pageIndex, PagerHelper.PageSize, count);//转换为PageList集合，用于分页控件显示不同的页码
            return View(pageList);//用pageList集合填充页面。
        }

        private IList<ICriterion> GetCondition()//生成查询条件,userName变量默认为空
        {
            List<ICriterion> queryConditions = new List<ICriterion>();//实例化一个查询条件集合
            queryConditions.Add(Expression.Not(Expression.Eq("Status", (int)TransportOrderStatus.WaitingForDispatch)));
            queryConditions.Add(Expression.Eq("Creator.ID", AppHelper.LoginedUser.ID));//按照当前登录人员的ID查询（只能查询到自己创建的货物运单）
            return queryConditions;//返回查询条件集合
        }

        public ActionResult Details(int ID)
        {
            TransportProvinceList();
            var tranportOrder = Container.Instance.Resolve<ITransportOrderService>().Get(ID);
            return View(tranportOrder);
        }

        #region 创建
        [HttpGet]
        public ActionResult Create()
        {
            TransportProvinceList();

            TransportOrder order = new TransportOrder();
            order.Receiver = new Client();
            order.Commisionedor = new Client();
            order.DeliveryType = DeliveryType.StationToStation;
            order.TranportOrderItems = new List<TransportOrderItem>();
            order.TranportOrderItems.Add(new TransportOrderItem());

            //return View(order);
            return View("Create", order);
        }

       
        /// <summary>
        /// 保存运货单
        /// </summary>
        /// <param name="tranportOrder"></param>
        /// <param name="deliveryTypeId"></param>
        /// <param name="selectItemValue"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(TransportOrder order, string txtCargoData,
            string txtStartSatationNameID = "", string txtDestionationNameID = "",
            string txtSendManID = "", string txtBillManID = "", string ddlStartSatationProvince="",string ddlDestionationProvince="")
        {
            Container.Instance.Resolve<ITransportOrderService>().Create(order, txtCargoData, txtStartSatationNameID, 
                ddlStartSatationProvince, txtDestionationNameID,ddlDestionationProvince, txtSendManID, txtBillManID);
            return RedirectToAction("Index");
        }
        #endregion

        #region 编辑
        public ActionResult Edit(int id)
        {
            TransportProvinceList();

            var tranportOrder = Container.Instance.Resolve<ITransportOrderService>().Get(id);
            return View("Create", tranportOrder);
        }

        [HttpPost]
        public ActionResult Edit(TransportOrder tranportOrder, string deliveryTypeId, string selectItemValue)
        {
            tranportOrder.TranportOrderItems = new List<TransportOrderItem>();
            //if (ModelState.IsValid)//如果user实体的数据合法
            //{
                SetOrderItem(tranportOrder, selectItemValue);
                tranportOrder.DeliveryType = (DeliveryType)int.Parse(deliveryTypeId);//将业务员选择的“运输方式”转换为枚举
                Container.Instance.Resolve<ITransportOrderService>().Update(tranportOrder);
                return RedirectToAction("Index");
            //}
            //TransportProvinceList();
            //return View("Create", tranportOrder);
        }
        #endregion

        #region 删除
        public ActionResult Delete(int id)
        {
            Container.Instance.Resolve<ITransportOrderService>().Delete(id);
            return RedirectToAction("Index");
        }

        [HttpPost]
        public ActionResult Delete(int id, TransportOrder tranportOrder)
        {
            Container.Instance.Resolve<ITransportOrderService>().Delete(id);
            return RedirectToAction("Index");
        }
        #endregion

        #region 扩展方法
        /// <summary>
        /// 设置内容项
        /// </summary>
        /// <param name="tranportOrder"></param>
        /// <param name="selectItemValue"></param>
        private void SetOrderItem(TransportOrder tranportOrder, string selectItemValue)
        {
            if (!string.IsNullOrEmpty(selectItemValue))
            {
                string[] row = selectItemValue.Split('_');
                string[] td;
                if (row != null && row.Length > 0)
                {
                    foreach (string r in row)
                    {
                        if (string.IsNullOrEmpty(r)) continue;

                        TransportOrderItem item = null;
                        td = r.Split(',');
                        int counter = 0;
                        decimal transportFee = 0;
                        if (td != null && td.Length == 8)
                        {
                            item = new TransportOrderItem();
                            item.CargoName = td[0];
                            item.CabinetSort = td[1];
                            item.CabinetType = td[2];
                            int.TryParse(td[3], out counter);
                            item.Counter = counter;
                            item.CabinetNumber = td[4];
                            item.SealedNumber = td[5];

                            decimal.TryParse(td[6], out transportFee);
                            item.TransportFee = transportFee;

                            item.ID = int.Parse(td[7]);
                        }
                        if (item != null)
                            tranportOrder.TranportOrderItems.Add(item);
                    }
                }
            }
        }

        /// <summary>
        /// 设置省份信息
        /// </summary>
        private void TransportProvinceList()
        {
            ViewBag.ProvinceList = Container.Instance.Resolve<IProvinceService>().GetAll();
        }

        #endregion

        #region 自动完成功能
        public string FindStation(string q, string provinceID)
        {
            IList<ICriterion> conditions = new List<ICriterion>();//定义一个查询条件变量
            if (!string.IsNullOrEmpty(provinceID))//如果省份id不为空
            {
                conditions.Add(Expression.Eq("Province.ID", int.Parse(provinceID)));//在变量中添加一个查询条件,根据省份的id查询,如：Province.ID=1
            }
            if (!string.IsNullOrEmpty(q))//如果文本框中的内容不为空
            {
                conditions.Add(Expression.Like("Name", "%" + q + "%"));//在变量中添加一个模糊查询条件，根据站的名称进行查询
            }
            IList<Station> list = Container.Instance.Resolve<IStationService>().Find(conditions);

            string name = string.Empty;
            foreach (Station station in list)
            {
                name += station.Name + "," + station.ID + "\n";//由于视图中只需要站名和ID就可以，其它信息不要,autocomplete以“\n”换行，所以站与站之间必须用“\n”分隔
            }
            return name;
        }

        public string FindClient(string q)
        {
            IList<ICriterion> conditions = new List<ICriterion>();
            if (!string.IsNullOrEmpty(q))
            {
                conditions.Add(new LikeExpression("Name", q + "%"));
            }
            IList<Client> list = Container.Instance.Resolve<IClientService>().Find(conditions);
            string name = string.Empty;
            foreach (Client c in list)
            {
                name += c.Name + "," + c.Telephone + "," + c.Address + "," + c.PostNumber + "," + c.Email + "," + c.ID + "\n";
            }
            return name;
        }

        public string FindAddress(string q)
        {
            IList<ICriterion> conditions = new List<ICriterion>();
            if (!string.IsNullOrEmpty(q))
            {
                conditions.Add(new LikeExpression("StartStationLocation", "%" + q + "%"));
            }
            IList<TransportOrder> list = Container.Instance.Resolve<ITransportOrderService>().Find(conditions);
            string name = string.Empty;
            foreach (TransportOrder entity in list)
            {
                name += entity.StartStationLocation + "\n";
            }
            return name;
        }
        #endregion
    }
}
